var mongoose = require('mongoose');
var News = require('../models/news.model')// 引数据模型

// 新增
exports.create = function(req,res,next){
    var news = new News(req.body); // 从req.body里获取参数对象，比如{name:'vane',gender:'男',city:'杭州'....}

    news.save()
    .then(data=>{
        res.json(data)
    })
    
}
exports.get = function(req,res,next){
    var id =req.params.id; // 从req.body里获取参数对象，比如{name:'vane',gender:'男',city:'杭州'....}
    console.log(id);
    News.findById(id,function(err,result){
        console.log(result);
        res.json(result);
    });
}
//修改
exports.update = function(req,res,next){
  
    var id = req.params.id; // req.param('id')
    // 现在操作的都是mongoose而不是mongodb
    News.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
    .then(data=>{
        res.json({msg:'数据修改成功',status:200}); // 如果你要返回数据，这个data返回的是你之前修改的那个数据内容
    })
}

//删除
exports.remove = function(req,res,next){
    var id = req.params.id;
    News.findByIdAndRemove(id,function(err,doc){
        res.json({msg:'数据删除成功',status:200})
    })
} 
exports.removes = function(req,res,next){
    var ids = req.params.ids;
    ids=ids.split(',');
    console.log(ids);
    News.remove({_id:{$in:ids}}).then(data=>{
        res.json(data);
    })
} 

exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page : 1;
    var rows = (req.body.rows) ? req.body.rows : 2;
    var queryCondition = {};
    var title,ftitle,content,author;
    if( req.body.title && req.body.title.trim().length>0 ){
        title = req.body.title;
        queryCondition = {"title":new RegExp(title,'i')}
    }

    if( req.body.ftitle && req.body.ftitle.trim().length>0 ){
        ftitle = req.body.ftitle;
        queryCondition = {"ftitle":new RegExp(ftitle,'i')}
    }

    if( req.body.content && req.body.content.trim().length>0 ){
        content = req.body.content;
        queryCondition = {"content":new RegExp(content,'i')}
    }

    if( req.body.author && req.body.author.trim().length>0 ){
        author = req.body.author;
        queryCondition = {"author":new RegExp(author,'i')}
    }

    if(req.body.cateId && req.body.cateId.trim().length>0){
        cateId = req.body.cateId;
        queryCondition = Object.assign(queryCondition,{
            "cateId" : cateId
        })
    }

    if(req.body.userId && req.body.userId.trim().length>0){
        userId = req.body.userId;
        queryCondition = Object.assign(queryCondition,{
            "userId" : userId
        })
    }
    
    //Object.assign对象合并

    console.log("queryCondition",queryCondition)


    News.paginate(queryCondition, { page: page, limit: parseInt(rows) }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}

